import { useState, useRef } from 'react'
import './App.css'

function App() {
  // 火山引擎tts 配置文件
  const { VITE_TOKEN, VITE_APP_ID, VITE_CLUSTER_ID } = import.meta.env;

  //代码的可读性高于一切
  const [prompt, setPrompt] = useState('大家好，我是xxx');
  // 状态 ready waiting done 界面由数据状态驱动
  const [status, setStatus] = useState(false);

  // react use 开头 ref hook 可以获取DOM元素
  const audioPlayer = useRef(null)

  // console.log(audioPlayer)

  function createBlobURL(base64AudioData) {
    var byteArrays = []; 
    var byteCharacters = atob(base64AudioData); 
    for (var offset = 0; offset < byteCharacters.length; offset++) { 
      var byteArray = byteCharacters.charCodeAt(offset); 
      byteArrays.push(byteArray); 
    } 
    var blob = new Blob([new Uint8Array(byteArrays)], { type: 'audio/mp3' }); 
    return URL.createObjectURL(blob);
  }

  const playMusic = () => {
    console.log('play music');
    audioPlayer.current.play();
  }

  const generateAudio = () => {
    const voiceName = "zh_male_xionger_mars_bigtts";
    const endpoint = "/tts/api/v1/tts" // tts api llm 服务接口地址
    const headers = {
      'Content-Type': 'application/json',
      Authorization: `Bearer;${VITE_TOKEN}`,
    }
    const payload = {
      app: {
        appid: VITE_APP_ID,
        token: VITE_TOKEN,
        cluster: VITE_CLUSTER_ID,
      },
      user: {
        uid: 'fogletter',
      },
      audio: {
        voice_type: voiceName,
        encoding: 'ogg_opus', // 编码格式
        compression_rate: 1,// 压缩率
        rate: 16000, // 采样率
        speed_radio: 1, // 语速
        volume_radio: 1, // 音量
        pitch_radio: 1, // 音调
        emotion: 'happy', // 情感
      },
      request: {
        reqid: Math.random().toString(36).substring(7),
        text: prompt,
        text_type: 'plain',
        operation: 'query',
        silence_duration: '125',
        with_frontend: '1',
        frontend_type: 'unitTson',
        pure_english_opt: '1'
      }
    }
    setStatus('waiting');
    fetch(endpoint, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(payload),
    }).then(response => response.json())
      .then(data => {
        // console.log(data);
        // 黑盒子 base64 字符串编码的格式表达图片，声音，视频
        // 编解码的问题
        const url = createBlobURL(data.data); // 返回一个可以播放声音的url
        audioPlayer.current.src = url;
        audioPlayer.current.play();
        setStatus('done');
      })
  }





  return (
    <div className='container'>
      <div>
        <label>Prompt</label>
        <button onClick={generateAudio}>生成并播放</button>
        <textarea
          className='input'
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
        >
        </textarea>
      </div>
      {/* <audio ref={audioPlayer} src="/sounds/snare.wav"></audio> */}
      {/* <button onClick={playMusic}>播放</button> */}
      <div className="out">
        <div>{status}</div>
        <audio ref={audioPlayer}></audio>
      </div>
    </div>
  )
}

export default App
